package Hot100;

import LinkedList.ListNode;

public class K个一组翻转链表 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dHead = new ListNode(-1, head);
        ListNode pre = dHead, start = head, nHead = head;
        while (true) {
            for (int i = 0; i < k; i++) {
                if (nHead != null) nHead = nHead.next;
                else return dHead.next;
            }
            pre.next = reverseList(start, nHead);
            pre = start;
            start = nHead;
        }
    }

    private ListNode reverseList(ListNode head, ListNode tail) {
        ListNode prev;
        ListNode curr = head;
        ListNode aftr = head.next;
        curr.next = tail;
        while (aftr != tail) {
            prev = curr;
            curr = aftr;
            aftr = aftr.next;
            curr.next = prev;
        }
        return curr;
    }
}
